package tm.testing;

import com.jme.input.MouseInput;
import com.jme.input.action.InputActionEvent;
import com.jme.input.action.MouseInputAction;
import com.jme.intersection.BoundingPickResults;
import com.jme.intersection.PickResults;
import com.jme.intersection.TrianglePickResults;
import com.jme.math.Ray;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.scene.Node;
import com.jme.scene.TriMesh;
import com.jme.system.DisplaySystem;

public class MouseSelect extends MouseInputAction {
	
	//The game's mouse state as a reference
	private MouseState mouseState;
	//The scene in which to compute mouse interaction
	private Node scene;
	//The user's camera
	private Camera camera;
	
	private DisplaySystem display;
	
	//The mouse's position at last check
	private int mouse_x;
	private int mouse_y;

	
	public MouseSelect(MouseState ms, Node scene, Camera camera, DisplaySystem display) {
		this.mouseState = ms;
		this.scene = scene;
		this.camera = camera;
		this.display = display;
		mouse_x = 0;
		mouse_y = 0;
	}
	
    public void performAction(InputActionEvent evt) {	
    	if(MouseInput.get().isButtonDown(0)) {
    		mouse_x = MouseInput.get().getXAbsolute();
    		mouse_y = MouseInput.get().getYAbsolute();
    		
    		mouseState.setMousePosition(new Coordinate(mouse_x, mouse_y));
    		
    		Vector2f screenPos = new Vector2f(mouse_x, mouse_y);
    		Vector3f startPoint = DisplaySystem.getDisplaySystem().getWorldCoordinates(screenPos, 0);
    		// Get the world location of that X,Y value - far
    		Vector3f endPoint = DisplaySystem.getDisplaySystem().getWorldCoordinates(screenPos, 1);
    		Ray ray = new Ray(startPoint, endPoint.subtract(startPoint));
    		TrianglePickResults results =  new TrianglePickResults();
    		results.setCheckDistance(true);
    		results.clear();
    		scene.findPick(ray, results);
    		
    		
    		for(int pickIndex = 0; pickIndex < results.getNumber(); pickIndex++) {
    			System.out.println("AHA: "+results.getPickData(pickIndex).getTargetMesh().getName());
    			mouseState.setMouseOverGeometry(results.getPickData(pickIndex).getTargetMesh());
    		}
    	}
	}
}
